package com.v0710.module.oss.service.handler;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.v0710.module.admin.entity.SysOss;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @description：阿里oss文件上传处理器
 * @author：yufan.wang
 * @create：2024/1/5 20:42
 */
@Slf4j
@Component(value = "aliFileStorageHandler")
public class AliFileStorageHandler implements FileStorageHandler {

    /**
     * 文件上传至阿里云
     *
     * @param file 文件
     * @return String
     */
    @Override
    public String uploadFile(MultipartFile file, SysOss sysOss) {

        String uploadUrl = "";

        try {

            //判断oss实例是否存在，如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(sysOss.getEndpoint(), sysOss.getAccessKey(), sysOss.getSecretKey());
            if (!ossClient.doesBucketExist(sysOss.getBucketName())) {
                //创建bucket
                ossClient.createBucket(sysOss.getBucketName());
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(sysOss.getBucketName(), CannedAccessControlList.PublicRead);
            }

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();
            //在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //把文件按照日期进行分类，构建日期路径: xpu-repair/2021/04/14
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName = datePath + "/" + uuid + fileName;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            //调用oss方法实现上传
            ossClient.putObject(sysOss.getBucketName(), fileName, inputStream, objectMetadata);
            //关闭ossClient
            ossClient.shutdown();
            //需要把上传到阿里云oss路径手动拼接出来
            uploadUrl = "https://" + sysOss.getName() + "." + sysOss.getEndpoint() + "/" + fileName;
            log.info("阿里云oss图片地址:{}", uploadUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadUrl;
    }

}
